#include "Model4GControlTask.h"
#include "Model4GApp.h"
#include "cmsis_os.h"

#include <string.h>

static void StartModel4GContorlTask(const void *pvParameters);
static void StartModel4GSetTask(const void *pvParameters);

osThreadId Model4GControlTaskHandle; 
osThreadDef(Model4GControlTaskId, StartModel4GContorlTask, osPriorityNormal, 1, 2048);

bool Model4GControlTaskInit(void)
{
	InitModelDriver();
	
	//创建数据指令执行任务
	Model4GControlTaskHandle = osThreadCreate(osThread(Model4GControlTaskId), NULL);
	if(Model4GControlTaskHandle == NULL)
	{
		return false;
	}
	
	return true;
}

static void StartModel4GContorlTask(const void *pvParameters)
{
	osEvent evt;
	uint32_t u32DataLength = 0;
	
	osMessageQId msgQnModel4GContrlMsgId = getModel4GControlMsgQueneID();
	Model4GConfigStep eModel4GCfgStp = eCheckModel4GStartup;
	
	bool bIsModelSetRes = false;
	
	while(1)
	{
		evt = osMessageGet(msgQnModel4GContrlMsgId, 5000);
		
		if (evt.status == osEventMessage)
		{
			u32DataLength = (uint32_t)evt.value.p;
			uint8_t *data = getModel4GBuff();
			
			switch(eModel4GCfgStp)
			{
				case eCheckModel4GStartup:
				{
					if(checkModelStartupStatus((const char *)data))
					{
						setModelStartupStatus(true);
						
						eModel4GCfgStp = eEnterCmdMode;
						usrSetEnterCmdMode();
					}
					break;
				}
				
				case eEchoModeOff:
				{
					if(bIsModelSetRes)
					{
						if(strstr((const char *)data, "+OK") == NULL)
						{
							eModel4GCfgStp = eSetServerB;
							usrSetSocketBLongMode();
						}
						bIsModelSetRes = false;
					}
					else
					{
						setModelEchoStatus(false);
						bIsModelSetRes = true;
					}
					break;
				}
				
				case eEnterCmdMode:
				{
					if(bIsModelSetRes)
					{
						if(strstr((const char *)data, "+OK") == NULL)
						{
							usrSetModelEchoStatus(true);
							eModel4GCfgStp = eEchoModeOff;
						}

						bIsModelSetRes = false;
					}
					else
					{
						if(data[0] != 'a')
						{
							osDelay(500);
							setModelEnterCmdStatus(data[0], 0);
							bIsModelSetRes = false;
						}
						else
						{
							setModelEnterCmdStatus(data[0], 1);
							bIsModelSetRes = true;
						}
					}

					
					break;
				}
				
				case eSetServerB:
				{
					if(bIsModelSetRes)
					{
						if(strstr((const char *)data, "+OK") == NULL)
						{
							bIsModelSetRes = false;
							eModel4GCfgStp = eEnterByPassMode;
						}
					}
					else
					{
						setSockB();
						bIsModelSetRes = true;
					}
					break;
				}
				case eEnterByPassMode:
				{
					if(bIsModelSetRes)
					{
						if(strstr((const char *)data, "+OK") == NULL)
						{
							bIsModelSetRes = false;
							eModel4GCfgStp = eConfigDone;
						}
					}
					else
					{
						setModelEnterCmdStatus(false, 0);
						bIsModelSetRes = true;
					}
					break;
				}
				
				case eConfigDone:
				{
					setModelConfigStatus(true);
					break;
				}
			}
			
		}
	}
}

